package com.acme.bankapp.service.bank;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import com.acme.bankapp.domain.bank.AbstractAccount;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.bank.ClientExistsException;

import static com.acme.bankapp.net.bank.BankMessages.*;

/**
 * Implements bank service for operations with remote bank
 * @author Artem Nikitin
 *
 */
public class BankNetService implements IBankService {

	Socket requestSocket;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	String host;
	int port;
	BankService bankService;
	
	public BankNetService(String host, int port) throws UnknownHostException, IOException {
		this.host = host;
		this.port = port;
		requestSocket = new Socket(host, port);
		System.out.println("Connected to localhost in port " + port);
		out = new ObjectOutputStream(requestSocket.getOutputStream());
		out.flush();
		in = new ObjectInputStream(requestSocket.getInputStream());
	}

	/**
	 * Adds client to remote bank. 
	 * {@code bank} parameter is intentionally ignored for simplicity
	 */
	@Override
	public void addClient(Bank bank, Client client)
			throws ClientExistsException {
		try {
			out.writeObject(BMSG_CLIENT_ADD);
			out.writeObject(client);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Add account to client in remote bank. Client must exist in bank.
	 */
	@Override
	public void addAccount(Client client, AbstractAccount account) {
		try {
			out.writeObject(BMSG_ACCOUNT_ADD);
			out.writeObject(client);
			out.writeObject(account);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Search client in remote bank. 
	 * {@code bank} parameter is intentionally ignored for simplicity
	 */
	@Override
	public Client getClientByName(Bank bank, String name) {
		try {
			out.writeObject(BMSG_CLIENT_GET);
			out.writeObject(name);
			return (Client) in.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public void close() throws ClassNotFoundException, IOException {
		out.writeObject(BMSG_BYE);
		in.close();
		out.close();
		requestSocket.close();
	}
	
}
